package com.chenju.easyshotjava.core;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

public class ImagePanel extends JPanel {
    private BufferedImage image;
    private Point startPoint;
    private Rectangle currentRect;

    public ImagePanel(BufferedImage image) {
        this.image = image;
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                startPoint = e.getPoint();
                currentRect = null;
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (currentRect != null && startPoint != null) {
                    Graphics2D g2d = image.createGraphics();
                    g2d.setColor(Color.RED);
                    g2d.drawRect(currentRect.x, currentRect.y, currentRect.width, currentRect.height);
                    g2d.dispose();
                    repaint();
                }
                startPoint = null;
                currentRect = null;
            }
        });

        this.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                Point endPoint = e.getPoint();
                int x = Math.min(startPoint.x, endPoint.x);
                int y = Math.min(startPoint.y, endPoint.y);
                int width = Math.abs(startPoint.x - endPoint.x);
                int height = Math.abs(startPoint.y - endPoint.y);
                currentRect = new Rectangle(x, y, width, height);
                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
        if (currentRect != null) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(Color.RED);
            g2d.drawRect(currentRect.x, currentRect.y, currentRect.width, currentRect.height);
        }
    }
}